<script setup lang="ts">
import {
  getConsultOrderPayUrl,
  getConsultOrderPreService,
  getPatientInfoService,
  submitConsultOrderService,
} from '@/api/consult'
import type { ConsultOrderPreParams, ConsultOrderPreData } from '@/types/consult'
import { onMounted, ref } from 'vue'
import { useConsultStore } from '@/stores'
import type { Patient } from '@/types/user'
import { onBeforeRouteLeave, useRouter } from 'vue-router'
import { Dialog, Toast } from 'vant'
const router = useRouter()
const consultStore = useConsultStore()
const { type, illnessType } = consultStore.consult
const preParams = ref<ConsultOrderPreParams>({
  type,
  illnessType,
  // useCoupon: '1',
  // couponId: ''
})

// 1. 预支付订单信息
const preData = ref<ConsultOrderPreData>()
const getPreData = async () => {
  try {
    const res = await getConsultOrderPreService(preParams.value)
    preData.value = res
    // 设置默认优惠券
    consultStore.setCoupon(preData.value?.couponId)
  } catch (error) {
    console.log(error)
    router.replace('/')
  }
}

//  2. 获取患者详情
const patientInfo = ref<Patient>()
const getPatientInfo = async () => {
  try {
    if (!consultStore.consult.patientId) return
    const res = await getPatientInfoService(consultStore.consult.patientId)
    patientInfo.value = res
  } catch (error) {
    console.log(error)
  }
}

// 3. 支付协议
const isAgree = ref(false)

// 4. 提交订单
const loading = ref(false)
const orderId = ref('') // 订单id
const onSubmit = async () => {
  try {
    loading.value = true
    // 调用接口
    const res = await submitConsultOrderService(consultStore.consult)
    orderId.value = res.id
    // 订单创建成功后，清除store中数据，刷新页面接口请求异常，可以try/catch捕获跳回首页
    consultStore.clear()
    show.value = true // 弹出支付弹层
  } catch (error) {
    console.log(error)
  } finally {
    loading.value = false
  }
}

// 5. 选择支付方式
const show = ref(false) // 支付弹层是否显示
const paymentMethod = ref<0 | 1>() // 支付方式 0：微信支付 1：支付宝支付

/**
 * 需求：
  1. 生成订单后：不可回退，用户离开页面前确认
  2. 生成订单后：不可关闭支付抽屉
  3. 获取后台支付地址，跳转支付
 */
onBeforeRouteLeave(() => {
  if (orderId.value) return false
})

const onClose = () => {
  return Dialog.confirm({
    title: '关闭支付',
    message: '取消支付将无法获得医生回复，医生接诊名额有限，是否确认关闭？',
    cancelButtonText: '仍要关闭',
    cancelButtonColor: 'var(--cp-price)',
    confirmButtonText: '继续支付',
    confirmButtonColor: 'var(--cp-primary)',
  })
    .then(() => {
      return false
    })
    .catch(() => {
      orderId.value = '' // 清空后才能跳转页面
      router.push('/user/consult')
      return true
    })
}

// 跳转支付
import CpPaySheet from '@/components/CpPaySheet.vue'

onMounted(() => {
  getPreData()
  getPatientInfo()
})
</script>

<template>
  <div class="consult-pay-page">
    <cp-nav-bar title="支付" />
    <!-- 1. 支付信息 -->
    <div class="pay-info">
      <p class="tit">图文问诊 {{ preData?.payment || 0 }} 元</p>
      <img class="img" src="@/assets/avatar-doctor.svg" />
      <p class="desc">
        <span>极速问诊</span>
        <span>自动分配医生</span>
      </p>
    </div>
    <!-- 1. 支付信息 -->
    <van-cell-group>
      <van-cell title="优惠券" :value="`-¥${preData?.couponDeduction || 0}`" />
      <van-cell title="积分抵扣" :value="`-¥${preData?.pointDeduction || 0}`" />
      <van-cell title="实付款" :value="`¥${preData?.payment || 0}`" class="pay-price" />
    </van-cell-group>
    <div class="pay-space"></div>
    <!-- 2. 患者信息  -->
    <van-cell-group>
      <van-cell
        title="患者信息"
        :value="`${patientInfo?.name} | ${patientInfo?.genderValue} | ${patientInfo?.age}岁`"
      ></van-cell>
      <van-cell title="病情描述" :label="consultStore.consult.illnessDesc"></van-cell>
    </van-cell-group>
    <div class="pay-schema">
      <van-checkbox v-model="isAgree">我已同意 <span class="text">支付协议</span></van-checkbox>
    </div>
    <!-- 3. 打开支付弹层并创建问诊订单 -->
    <!-- 注意：van-submit-bar组件的price单位是分 -->
    <van-submit-bar
      button-type="primary"
      :price="(preData?.actualPayment || 0) * 100"
      button-text="立即支付"
      text-align="left"
      :disabled="!isAgree"
      tip="请先同意支付协议"
      tip-icon="info"
      :loading="loading"
      @submit="onSubmit"
    />
    <!-- 支付弹层 -->
    <cp-pay-sheet
      :order-id="orderId"
      v-model:show="show"
      :actual-payment="preData?.actualPayment"
      :onClose="onClose"
    ></cp-pay-sheet>
  </div>
</template>

<style lang="scss" scoped>
.consult-pay-page {
  padding: 46px 0 50px 0;
  .pay-info {
    display: flex;
    padding: 15px;
    flex-wrap: wrap;
    align-items: center;
    .tit {
      width: 100%;
      font-size: 16px;
      margin-bottom: 10px;
    }
    .img {
      margin-right: 10px;
      width: 38px;
      height: 38px;
      border-radius: 4px;
      overflow: hidden;
    }
    .desc {
      flex: 1;
      > span {
        display: block;
        color: var(--cp-tag);
        &:first-child {
          font-size: 16px;
          color: var(--cp-text2);
        }
      }
    }
  }
  .pay-price {
    ::v-deep() {
      .vam-cell__title {
        font-size: 16px;
      }
      .van-cell__value {
        font-size: 16px;
        color: var(--cp-price);
      }
    }
  }
  .pay-space {
    height: 12px;
    background-color: var(--cp-bg);
  }
  .pay-schema {
    height: 56px;
    display: flex;
    align-items: center;
    justify-content: center;
    .text {
      color: var(--cp-primary);
    }
  }
  ::v-deep() {
    .van-submit-bar__button {
      font-weight: normal;
      width: 160px;
    }
  }
}
// 支付弹层样式
.pay-type {
  .amount {
    padding: 20px;
    text-align: center;
    font-size: 16px;
    font-weight: bold;
  }
  .btn {
    padding: 15px;
  }
  .van-cell {
    align-items: center;
    .cp-icon {
      margin-right: 10px;
      font-size: 18px;
    }
    .van-checkbox :deep(.van-checkbox__icon) {
      font-size: 16px;
    }
  }
}
</style>
